﻿using System;
using System.Text.RegularExpressions;

namespace YouTubeDownloadExtension
{
    public sealed class VideoSource
    {
        private const string FormatTagPattern = @"itag=(?<itag>\d+)";

        public Uri Uri { get; private set; }
        public VideoQuality Quality { get; private set; }
        public VideoFormat Format { get; private set; }

        private VideoSource(Uri uri, VideoQuality quality, VideoFormat format)
        {
            Uri = uri;
            Quality = quality;
            Format = format;
        }

        internal static VideoSource FromUri(Uri uri)
        {
            var formatTag = GetFormatTagFromUri(uri);

            switch (formatTag)
            {
                case "38":
                    return new VideoSource(uri, VideoQuality.Original, VideoFormat.MP4);
                case "37":
                    return new VideoSource(uri, VideoQuality.HD1080, VideoFormat.MP4);
                case "22":
                    return new VideoSource(uri, VideoQuality.HD720, VideoFormat.MP4);
                case "18":
                    return new VideoSource(uri, VideoQuality.Medium, VideoFormat.MP4);
                case "45":
                    return new VideoSource(uri, VideoQuality.HD720, VideoFormat.WebM);
                case "44":
                    return new VideoSource(uri, VideoQuality.Large, VideoFormat.WebM);
                case "43":
                    return new VideoSource(uri, VideoQuality.Medium, VideoFormat.WebM);
                case "35":
                    return new VideoSource(uri, VideoQuality.Large, VideoFormat.Flash);
                case "34":
                    return new VideoSource(uri, VideoQuality.Medium, VideoFormat.Flash);
                case "5":
                    return new VideoSource(uri, VideoQuality.Small, VideoFormat.Flash);
                case "36":
                    return new VideoSource(uri, VideoQuality.Small, VideoFormat.Mobile);
                default:
                    return new VideoSource(uri, VideoQuality.None, VideoFormat.None);
            }
        }

        private static string GetFormatTagFromUri(Uri uri)
        {
            var match = Regex.Match(uri.Query, FormatTagPattern);
            return match.Groups["itag"].Value;
        }

        public override string ToString()
        {
            return Uri.ToString();
        }
    }
}
